import React from 'react'
import { Modal,Row,Col, message } from 'antd'
import service from '../../../service'
import Checkbox from 'antd/lib/checkbox/Checkbox'

export default function SetPower(props) {
  const [allPower,setAllPower]=React.useState([])
  const [role_power,setRole_power]=React.useState([])
  const [checkList,setCheckList]=React.useState([])
  React.useEffect(()=>{
    if(props.role_key===undefined){
      service.allPower().then((res)=>{
      setAllPower(res.data)
    })
    }
    service.role_power({data:props.role_key}).then((res)=>{
      setRole_power(res.data)
      setCheckList(res.data)
    })
  },[props.role_key])
  const checkChange = (e,power)=>{
    let checkbox = [...checkList]
    if(e.target.checked){
      checkbox.push(power)
    }else{
      checkbox=checkbox.filter((item)=>item.key!==power.key)
    }
    setCheckList(checkbox)
  }
  const ok = ()=>{
    let list =[]
    checkList.map((item)=>{
      list.push(item.key)
    })
    service.role_power_({role_key:props.role_key,power_key:list})
    service.role_power({data:props.role_key}).then((res)=>{
      setRole_power(res.data)
      setCheckList(res.data)
    })
    message.success('修改成功')
    props.close()
  }
  return (
    <Modal
      title='设置用户角色'
      destroyOnClose
      okText='设置'
      cancelText='取消'
      onCancel={()=>{
        props.close()
      }}
      visible={props.visible}
      onOk = {ok}
    >
      <h3 style={{color:'#ff4d4f',marginBottom:'10px'}}>给角色：<span style={{color:'#000000'}}>{props.role_name}</span>设置权限</h3>
      <hr/>
      <Row style={{marginTop:'20px'}}>
        {
          allPower.map((power,index)=>{
            power.false=false
            if(role_power.length!==0){
                role_power.map((power1)=>{
                  if(power1.key===power.key){
                    power.false=true
                  }
                })
            }
            return <Col span={8} key={power.key}><Checkbox key={power.key} onChange={(e)=>{checkChange(e,power)}} defaultChecked={power.false?true:false}>{power.des}</Checkbox></Col>
          })
        }
      </Row>
    </Modal>
  )
}
